const {exec} = require('../db/mysql')
const getList = (author, keyword) => {
    // 1=1占位符
    let sql= `select * from blogs where 1=1 `
    if(author){
        sql+= `and author='${author}' `
    }
    if(keyword){
        sql += `and title like '%${keyword}%' `
    }
    sql += `order by createtime desc;`
    
    return exec(sql)
}

// 
const getDetail = (id) => {
    const sql =  `select * from blogs where id='${id}'`
    return exec(sql).then(res =>{ 
        return res[0]
    })
}

const newBlog = (blogData = {}) => {
    console.log('blogData', blogData)
    const {title, content, author} = blogData
    const createTime = Date.now()

    // TODO 数据库属性顺序要保持一致 
    const sql = `
        insert into blogs (title, content, author, createtime)
        values ('${title}', '${content}', '${author}', '${createTime}')
    `
    return exec(sql).then(insertData => {
        console.log('insertData is', insertData)
        return {
            id: insertData.insertId
        }
    })
}

const updateBlog = (id, blogData = {}) => {
    console.log('更新博客', id, blogData)
    const {title, content} = blogData
    const sql = `
        update blogs set title='${title}', content='${content}' where id=${id}
    `
    return exec(sql).then((updateData)=>{
        // console.log('updateData is', updateData)
        if(updateData.affectedRows > 0){
            return true
        }
        return false
    })
}

const delBlog =(id, author)=> {
    const sql=`delete from blogs where id='${id}' and author='${author}'`
    return exec(sql).then(delData => {
        if(delData.affectedRows > 0){
            return true
        }
        return false
    })
}
module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}